package com.example.demo.controller;

import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.entity.User;
import com.example.demo.pojo.Result;
import com.example.demo.service.UserService;
import com.example.demo.utils.JWTUtil;
import com.example.demo.utils.ThreadLocalUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.filters.ExpiresFilter;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Pattern;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@Validated
@Api(tags = "用户管理相关接口")
public class UserController {

    @Resource
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //登录逻辑修改为：jwt存在redis中，拦截器验证+redis能获取到相同jwt，修改密码后redis删除jwt
    @ApiOperation(value = "登录", produces = "application/json")
    @GetMapping("/user/login")
    public Map<String, Object> login(@Validated User user) {
        log.info(user.getName());
        log.info(user.getPassword());
        Map<String, Object> map = new HashMap<>();
        try {
            User login = userService.login(user);
            Map<String, String> payload = new HashMap<>();
            payload.put("id", String.valueOf(login.getId()));
            payload.put("name", login.getName());
            payload.put("password", login.getPassword());

            // 生成token
            String token = JWTUtil.getToken(payload);
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);


            map.put("status", true);
            map.put("msg", "登录成功");
            map.put("token", token); // 响应token，存储在客户端
        } catch (Exception e) {
            log.info("登录失败...");
            map.put("status", false);
            map.put("msg", "登录失败");
        }
        return map;
    }

    @ApiOperation(value = "jwt测试", produces = "application/json")
    @PostMapping("/user/test")
    public Map<String, Object> test(HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtil.verify(token);
        String id = verify.getClaim("id").asString();
        String name = verify.getClaim("name").asString();
        log.info("用户id：{}", id);
        log.info("用户名: {}", name);

        //TODO:业务逻辑
        Map<String, Object> map = new HashMap<>();
        map.put("status", true);
        map.put("msg", "请求成功");
        return map;
    }

    @ApiOperation(value = "findById", produces = "application/json")
    @RequestMapping("/user/findById")
    public User findById(Integer id) {
        return userService.findById(id);
    }

    @ApiOperation(value = "注册", produces = "application/json")
    @GetMapping("/user/register")
    public Result<String> register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        return Result.success("success");
    }

    @ApiOperation(value = "jwtCreate", produces = "application/json")
    @RequestMapping("/user/jwtCreate")
    public Result<String> jwtCreate(String content) {
        Map<String, String> claims = new HashMap<String, String>();
        claims.put("content", content);
        return Result.success(JWTUtil.getToken(claims));
    }

    @ApiOperation(value = "jwtReceive", produces = "application/json")
    @RequestMapping("/user/jwtReceive")
    public Result jwtReceive(/*@RequestHeader(name = "Authorization")*/String token, HttpServletResponse httpServletResponse) {
        try {
            Map<String, Claim> claimMap = JWTUtil.getTokenInfo(token);
            //模拟拦截器一次性设置jwt信息，供controller使用，线程安全不会因并发产生冲突
            ThreadLocalUtil.set(claimMap);
            Map<String, Claim> claim = ThreadLocalUtil.get();
            //claimMap.forEach((key,value)->System.out.println(key+"\t"+value));
            String content = claim.get("content").asString();
            //System.out.println(content);
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.getOperations().delete(token);
            return Result.success(content);
        } catch (Exception e) {
            httpServletResponse.setStatus(401);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation(value = "updateURL", produces = "application/json")
    @PatchMapping("/user/updateURL")
    public Result<String> updateURL(@RequestParam @URL String avatarUrl) {
        return Result.success(avatarUrl);
    }

    @ApiOperation(value = "updatePWD", produces = "application/json")
    @PatchMapping("/user/updatePWD")
    public Result updatePWD(@RequestBody @Validated(User.Update.class) Map<String, String> params) {
        //应用update校验规则
        return Result.success(params);
    }

    @ApiOperation(value = "upload", produces = "application/json")
    @PostMapping("/user/upload")
    public Result upload(MultipartFile file) throws IOException {

        String fileName = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        String name = uuid + fileName.substring(fileName.lastIndexOf("."));
        file.transferTo(new File("D:\\" + name));
        return Result.success("");
    }


}
